package com.api.viewModel;

import android.annotation.SuppressLint;
import android.app.Application;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.activity.App;
import com.activity.bean.CategoryBean;
import com.activity.bean.OssBean;
import com.activity.bean.TagBean;
import com.activity.bean.UserBean;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.api.LoginApi;
import com.api.StoreApi;
import com.api.param.AddWorkParam;
import com.api.param.ChangePwdParam;
import com.api.param.CommentParam;
import com.api.param.LoginParam;
import com.api.param.MobileParam;

import com.api.param.PageParam;
import com.api.param.RankParam;
import com.api.param.RemarkParam;
import com.api.param.UpdateUserParam;
import com.api.param.UserParam;
import com.api.response.BaseResponse;
import com.api.response.BaseResponsePredicate;
import com.api.response.OpusResponse;
import com.api.response.RemarkResponse;

import com.example.http.BuildFactory;



import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import org.greenrobot.eventbus.EventBus;

import event.MessageEvent;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.activity.App.BucketName;
import static com.activity.App.OSSURL;

public class LoginVM extends BaseResponseViewModel {

    public final MutableLiveData<ArrayList<CategoryBean>> categorys = new MutableLiveData<>();
    public LoginVM(@NonNull Application application) {
        super(application);
    }
    public final MutableLiveData<ArrayList<TagBean>> tags = new MutableLiveData<>();
    public final MutableLiveData<BaseResponse<String>> code = new MutableLiveData<>();
    public final MutableLiveData<UserBean> user = new MutableLiveData<>();
    public final MutableLiveData<Boolean> setPwd = new MutableLiveData<>();
    public final MutableLiveData<Boolean> workError = new MutableLiveData<>();
    public final MutableLiveData<OpusResponse> work = new MutableLiveData<>();
    public final MutableLiveData<Boolean> addWork = new MutableLiveData<>();
    public final MutableLiveData<Boolean> updateWork = new MutableLiveData<>();

    public final MutableLiveData<OpusResponse> workDetail = new MutableLiveData<>();
    public final MutableLiveData<Boolean> workRemarkError = new MutableLiveData<>();
    public final MutableLiveData<Boolean> resetPwd = new MutableLiveData<>();
    public final MutableLiveData<OssBean> oss = new MutableLiveData<>();
    public final MutableLiveData<String> comment = new MutableLiveData<>();
    public final MutableLiveData<Integer> praisePosition = new MutableLiveData<>();
    public final MutableLiveData<String> praise = new MutableLiveData<>();
    public final MutableLiveData<String> deleteWorks = new MutableLiveData<>();
    public final MutableLiveData<Boolean> updateUserinfo = new MutableLiveData<>();
    public final MutableLiveData<Boolean> ossError = new MutableLiveData<>();
    public final MutableLiveData<RemarkResponse> workRemark = new MutableLiveData<>();
    public final MutableLiveData<Boolean> authBean = new MutableLiveData<>();
    public  Disposable getMessageCode (MobileParam param){
        progress.setValue(true);

        return BuildFactory.getService(LoginApi.class).getMessageCode(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    progress.setValue(false);

                    if(res.isSuccess()){


                        code.setValue(res);
                        onError(new Throwable(res.getMessage()));
                    }
                },throwable -> {
                    onError(throwable);
                    code.setValue(null);
                });
    }

     //登录

    public  Disposable login (LoginParam param){
        progress.setValue(true);

        return BuildFactory.getService(LoginApi.class).login(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    progress.setValue(false);

                    if(res.isSuccess()){


                        if(res.getResult().size()>0){
                            user.setValue(res.getResult().get(0));
                        }else {
                            onError(new Throwable(res.getMessage()));
                        }


                    }
                },throwable -> {
                    onError(throwable);

                });
    }
    public  Disposable login1 (LoginParam param){


        return BuildFactory.getService(LoginApi.class).login(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {


                    if(res.isSuccess()){


                        if(res.getResult().size()>0){
                            user.setValue(res.getResult().get(0));
                        }else {
                            onError(new Throwable(res.getMessage()));
                        }


                    }
                },throwable -> {
                    onError(throwable);

                });
    }
    //登录

    public  Disposable getPersonInfo (LoginParam param){
        progress.setValue(true);

        return BuildFactory.getService(LoginApi.class).getPersonInfo(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    progress.setValue(false);
                    res.getResult().get(0).setPwd(App.getInstance().getAccount().getPwd());
                    App.getInstance().setAccount(res.getResult().get(0));
                    updateUserinfo.setValue(true);
                    EventBus.getDefault().post(new MessageEvent(MessageEvent.MESSAGE_EVENT_UPDATE_USER));
                },throwable -> {
                    onError(throwable);

                });
    }
    //注册
    public  Disposable register (LoginParam param){
        progress.setValue(true);

        return BuildFactory.getService(LoginApi.class).register(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    progress.setValue(false);

                    if(res.isSuccess()){


                        if(res.getResult().size()>0){
                            user.setValue(res.getResult().get(0));
                        }else {
                            onError(new Throwable(res.getMessage()));
                        }


                    }
                },throwable -> {
                    onError(throwable);

                });
    }
    //重置密码
    public  Disposable resetPwd (LoginParam param){
        progress.setValue(true);

        return BuildFactory.getService(LoginApi.class).setNewpassword(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    progress.setValue(false);
                    setPwd.setValue(true);
                    onError(new Throwable(res.getMessage()));
                },throwable -> {
                    setPwd.setValue(false);
                    onError(throwable);

                });
    }
    //作品列表
    public  Disposable getWork (PageParam param,boolean isHeader){


        return BuildFactory.getService(LoginApi.class).getWorkList(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    res.isHeader = isHeader;
                    work.setValue(res);

                },throwable -> {

                    workError.setValue(isHeader);

                    onError(throwable);
                });
    }

    //作品列表
    public  Disposable getWorkHome (PageParam param,boolean isHeader){


        return BuildFactory.getService(LoginApi.class).getWorkListHome(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    res.isHeader = isHeader;
                    work.setValue(res);

                },throwable -> {

                    workError.setValue(isHeader);

                    onError(throwable);
                });
    }

    //作品列表
    public  Disposable workDetail (RemarkParam param){


        progress.setValue(true);
        return BuildFactory.getService(LoginApi.class).workDetail(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    progress.setValue(false);
                    workDetail.setValue(res);

                },throwable -> {



                    onError(throwable);
                });
    }
    //评论列表
    public  Disposable getWorksReplyList (PageParam param,boolean isHeader){


        return BuildFactory.getService(LoginApi.class).getWorksReplyList(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    res.isHeader = isHeader;
                    workRemark.setValue(res);

                },throwable -> {

                    workRemarkError.setValue(isHeader);

                    onError(throwable);
                });
    }

    //重置密码
    public  Disposable addworks (AddWorkParam param){
        progress.setValue(true);

        return BuildFactory.getService(LoginApi.class).addworks(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    progress.setValue(false);
                    addWork.setValue(true);
                    onError(new Throwable(res.getMessage()));
                },throwable -> {

                    onError(throwable);

                });
    }

    public  Disposable updateworks (AddWorkParam param){
        progress.setValue(true);

        return BuildFactory.getService(LoginApi.class).updateworks(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    progress.setValue(false);
                    updateWork.setValue(true);
                    onError(new Throwable(res.getMessage()));
                },throwable -> {

                    onError(throwable);

                });
    }
    //评论列表
    public  Disposable getOss (){


        return BuildFactory.getService(LoginApi.class).getOss().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {

                 if(res.getResult().size()>0){
                     oss.setValue(res.getResult().get(0));
                 }else {
                     ossError.setValue(true);
                 }

                },throwable -> {


                    ossError.setValue(true);

                });
    }

    public void   uplaodImages(ArrayList < String> path, ImageResult resultImage,String key){


        if(App.getInstance().oss==null)
            return;
        progress.setValue(true);
        ArrayList<String> list = new ArrayList();
        ArrayList<String> images = new ArrayList();
        for (int i =0;i<path.size();i++){
// 构造上传请求。
            String okey = key+"/"+System.currentTimeMillis()+i+".png";
            PutObjectRequest put = new PutObjectRequest(BucketName, okey, path.get(i));



            OSSAsyncTask task = App.getInstance().oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest request, PutObjectResult result) {

                    Handler mainHandler = new Handler(Looper.getMainLooper());
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            //已在主线程中，可以更新UI
                            list.add (put.getUploadFilePath());
                            images.add(OSSURL+okey);
                            if(list.size()==path.size()){
                                if(resultImage!=null){
                                    resultImage.result(images,list);

                                }
                                progress.setValue(false);
                            }
                        }
                    });



                }

                @Override
                public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                    Handler mainHandler = new Handler(Looper.getMainLooper());
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            //已在主线程中，可以更新UI
                            list.add("");
                            if(list.size()==path.size()){
                                if(resultImage!=null){
                                    resultImage.result(images,list);
                                }
                                progress.setValue(false);
                            }
                        }
                    });
                }
            });
        }




    }

    //
    public  Disposable addworksreply (CommentParam param){
        progress.setValue(true);

        return BuildFactory.getService(LoginApi.class).addworksreply(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    progress.setValue(false);
                    comment.setValue(res.getResult());
                },throwable -> {

                    onError(throwable);

                });
    }
    //
    public  Disposable addworkspraise (CommentParam param,int position){


        return BuildFactory.getService(LoginApi.class).addworkspraise(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {

                    praise.setValue(res.getResult());
                    praisePosition.setValue(position);
                },throwable -> {

                    onError(throwable);

                });
    }

    public  Disposable deleteWorks (CommentParam param){
        progress.setValue(true);

        return BuildFactory.getService(LoginApi.class).deleteworks(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    progress.setValue(false);
                    deleteWorks.setValue(res.getResult());
                    onError(new Throwable(res.getMessage()));
                },throwable -> {

                    onError(throwable);

                });
    }

    public  Disposable updateUserinfo (UpdateUserParam param){
        progress.setValue(true);

        return BuildFactory.getService(LoginApi.class).updateUserinfo(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    progress.setValue(false);
                    res.getResult().get(0).setPwd(App.getInstance().getAccount().getPwd());
                    App.getInstance().setAccount(res.getResult().get(0));
                    updateUserinfo.setValue(true);
                    EventBus.getDefault().post(new MessageEvent(MessageEvent.MESSAGE_EVENT_UPDATE_USER));

                },throwable -> {

                    onError(throwable);

                });
    }

    public  Disposable resetPassword (ChangePwdParam param){
        progress.setValue(true);

        return BuildFactory.getService(LoginApi.class).resetPassword(json(param)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {
                    progress.setValue(false);
                    resetPwd.setValue(true);
                    onError(new Throwable(res.getMessage()));
                },throwable -> {

                    onError(throwable);

                });
    }

    public  Disposable getToken (){
        progress.setValue(true);

        return BuildFactory.getBaiduService(LoginApi.class).getToken().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(res -> {
                    App.getInstance().authBean = res;
                    authBean.setValue(true);


                    onError(new Throwable());
                },throwable -> {

                    onError(throwable);

                });
    }

    public interface  ImageResult{

        public  void  result(ArrayList<String> result,ArrayList<String> origin);
    }
    public  Disposable getTag (RankParam param){



        return BuildFactory.getService(StoreApi.class).getTags(json(param) ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {


                    tags.setValue(res.getResult());


                },throwable -> {

                    onError(throwable);

                });
    }
    public  Disposable getCategory (UserParam param){



        return BuildFactory.getService(StoreApi.class).getCategory(json(param) ).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .filter(new BaseResponsePredicate())
                .subscribe(res -> {


                    categorys.setValue(res.getResult());


                },throwable -> {

                    categorys.setValue(null);
                    onError(throwable);

                });
    }


}
